package com.base.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseListAdapter<T, VH extends BaseListAdapter.ViewHolder> extends BaseAdapter {
    private List<T> arrayList = new ArrayList<>();
    private AdapterCallback callback;

    public BaseListAdapter() {
        this(null);
    }

    public BaseListAdapter(@Nullable List<T> arrList) {
        changedList(arrList);
    }

    public void addCallback(@Nullable AdapterCallback callback) {
        this.callback = callback;
    }

    public void notifyEmpty() {
        notifyList(null);
    }

    public void callbackNotify(int what, Object tag) {
        if (null != callback)
            callback.onAdapterCallback(what, tag);
    }

    public void notifyList(@Nullable List<T> arrList) {
        changedList(arrList);
        notifyDataSetChanged();
    }

    public void changedList(List<T> arrList) {
        if (null == arrList)
            arrList = new ArrayList<>();
        arrayList = arrList;
    }

    @Override
    public T getItem(int position) {
        return arrayList.get(position);
    }

    @Override
    public int getCount() {
        return arrayList.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public List<T> getList() {
        return arrayList;
    }

    public View getConvertView(ViewGroup parent) {
        Context mContext = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(mContext);
        return inflater.inflate(adapterLayout(), parent, false);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        VH holder;
        if (convertView == null) {
            convertView = getConvertView(parent);
            holder = createViewHolder(convertView);
            convertView.setTag(holder);
        } else //noinspection unchecked
            holder = (VH) convertView.getTag();
        onViewHolder(holder, position);
        return convertView;
    }

    protected abstract void onViewHolder(VH vh, int position);

    public abstract int adapterLayout();

    public abstract VH createViewHolder(View view);

    public abstract static class ViewHolder {
        @NonNull
        public final View itemView;

        public ViewHolder(@NonNull View view) {
            if (view == null) {
                throw new IllegalArgumentException("itemView may not be null");
            }
            this.itemView = view;
        }
    }

}